package server

import (
	"context"
	"git.huoys.com/middle-business/xds/internal/model"
	v2 "github.com/envoyproxy/go-control-plane/envoy/api/v2"
	"github.com/envoyproxy/go-control-plane/pkg/cache"
	"google.golang.org/grpc/peer"
	"log"
	"time"
)

func (s *Server) FetchRoutes(context.Context, *v2.DiscoveryRequest) (*v2.DiscoveryResponse, error) {
	panic("Not implemented")
}

func (s *Server) StreamRoutes(stream v2.RouteDiscoveryService_StreamRoutesServer) error {
	clientPeer, ok := peer.FromContext(stream.Context())
	clientIP := "unknown"
	if ok {
		clientIP = clientPeer.Addr.String()
	}
	log.Printf("[%s] -------------- Starting a %s stream from %s ------------------\n", model.SUBSCRIBE_RDS, model.SUBSCRIBE_RDS, clientIP)

	for {
		req, err := stream.Recv()
		if err != nil {
			log.Println("[StreamRoutes] Recv fail, msg: ", err.Error())
			return err
		}
		log.Printf("[StreamRoutes] recv version %s ResourceNames %s TypeUrl %s", req.VersionInfo, req.ResourceNames, req.TypeUrl)
		routes := s.LoadRoutes()
		resp :=  &v2.DiscoveryResponse{VersionInfo: model.VERSION, TypeUrl: cache.RouteType}
		resp.Resources = routes
		log.Println("[StreamRoutes] resp: ", resp)
		stream.Send(resp)
		time.Sleep(time.Minute)
	}
}
